<template>
  <div class="containers" ref="content">
    <a-button-group>
      <a-button @click="handleUndo">
        <a-icon type="left" />撤销
      </a-button>
      <a-button @click="handleRedo">
        前进
        <a-icon type="right" />
      </a-button>
      <a-button @click="handleDownload">
        下载XML
        <a-icon type="download" />
      </a-button>
      <a-button @click="saveSVG">
        下载SVG
        <a-icon type="picture" />
      </a-button>
      <a-upload
        name="file"
        :multiple="false"
        :showUploadList="false"
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        :headers="headers"
        @change="handleChange"
      >
        <a-button>
          <a-icon type="folder-open" />导入
        </a-button>
      </a-upload>
    </a-button-group>
    <div class="canvas" ref="canvas"></div>
    <properties-view class="bpmn-modeler" v-if="bpmnModeler" :modeler="bpmnModeler"></properties-view>
  </div>
</template>

<script>
// 引入相关的依赖
// import BpmnViewer from 'bpmn-js'
import BpmnModeler from "bpmn-js/lib/Modeler";
import PropertiesView from "./custom-properties-panel/PropertiesView";

import { xmlStr } from "../mock/xmlStr";
export default {
  name: "",
  components: {
    PropertiesView
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 载入后, Vue 实例挂载到实际的 DOM 操作完成，一般在该过程进行 Ajax 交互
  mounted() {
    this.init();
  },
  data() {
    return {
      // bpmn建模器
      bpmnModeler: null,
      container: null,
      canvas: null,
      headers: {
        authorization: "authorization-text"
      }
    };
  },
  // 方法集合
  methods: {
    init() {
      // 获取到属性ref为“content”的dom节点
      this.container = this.$refs.content;
      // 获取到属性ref为“canvas”的dom节点
      const canvas = this.$refs.canvas;
      // 建模
      this.bpmnModeler = new BpmnModeler({
        container: canvas
      });
      this.createNewDiagram();
    },
    createNewDiagram() {
      // 将字符串转换成图显示出来
      this.bpmnModeler.importXML(xmlStr, err => {
        if (err) {
          // console.error(err)
        } else {
          // 这里是成功之后的回调, 可以在这里做一系列事情
          this.success();
        }
      });
    },
    success() {
      // 给图绑定事件，当图有发生改变就会触发这个事件
      const that = this;
      this.bpmnModeler.on("commandStack.changed", function() {
        that.saveDiagram(function(err, xml) {
          console.log(xml);
        });
      });
    },
    // 下载为bpmn格式,done是个函数，调用的时候传入的
    saveDiagram(done) {
      // 把传入的done再传给bpmn原型的saveXML函数调用
      this.bpmnModeler.saveXML({ format: true }, function(err, xml) {
        done(err, xml);
      });
    },
    // 后退
    handleUndo() {
      this.bpmnModeler.get("commandStack").undo();
    },
    // 前进
    handleRedo() {
      this.bpmnModeler.get("commandStack").redo();
    },
    // 下载为SVG格式,done是个函数，调用的时候传入的
    saveSVG() {
      // 把传入的done再传给bpmn原型的saveSVG函数调用
      this.bpmnModeler.saveSVG({ format: true }, (err, data) => {
        const dataTrack = "svg";
        const a = document.createElement("a");
        const name = `diagram.${dataTrack}`;
        a.setAttribute(
          "href",
          `data:application/bpmn20-xml;charset=UTF-8,${encodeURIComponent(
            data
          )}`
        );
        a.setAttribute("target", "_blank");
        a.setAttribute("dataTrack", `diagram:download-${dataTrack}`);
        a.setAttribute("download", name);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      });
    },
    handleDownload() {
      this.bpmnModeler.saveXML({ format: true }, (err, data) => {
        const dataTrack = "xml";
        const a = document.createElement("a");
        const name = `diagram.${dataTrack}`;
        a.setAttribute(
          "href",
          `data:application/bpmn20-xml;charset=UTF-8,${encodeURIComponent(
            data
          )}`
        );
        a.setAttribute("target", "_blank");
        a.setAttribute("dataTrack", `diagram:download-${dataTrack}`);
        a.setAttribute("download", name);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      });
    },
    handleChange(info) {
      // if (info.file.status !== "uploading") {
      //   console.log(info.file.originFileObj);
      // }
      if (info.file.status === "done") {
        const reader = new FileReader();
        let data = "";
        reader.readAsText(info.file.originFileObj);
        reader.onload = event => {
          data = event.target.result;
          this.bpmnModeler.importXML(data, err => {
            if (err) {
              this.$message.info(`${info.file.name} 导入失败`);
            } else {
              this.$message.success(`${info.file.name} 导入成功`);
            }
          });
        };
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败`);
      }
    }
  },

  // 计算属性
  computed: {}
};
</script>

<style scoped>
.containers {
  background-color: #ffffff;
  width: 100%;
  height: calc(100%);
}
.canvas {
  width: 100%;
  height: 100%;
  /* border: 4mm ridge rgba(170, 50, 220, .6); */
}
.panel {
  position: absolute;
  right: 0;
  top: 0;
  width: 300px;
}
.bpmn-modeler {
  margin-top: 88px;
  margin-right: 16px;
  /* background-color: #f0f2f5; */
  background-color: #ffffff;
}
</style>